package CSP;

import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;

public class FOV {

    public double[] xpoints;
    public double[] ypoints;

    public FOV(int camInd, double angle, ArrayList<Point2D.Double> cameras, int range0, int range1) {
        double camX = cameras.get(camInd).x;
        double camY = cameras.get(camInd).y;
        AffineTransform t = new AffineTransform();
        t.rotate(angle, camX, camY);

        //HERE IS THE 45 Degree 505 , 505
        Point2D.Double[] pArr = {new Point2D.Double(camX, camY),
            new Point2D.Double(camX + 710, camY),
            new Point2D.Double(camX + range0, camY + range1)};


        t.transform(pArr, 0, pArr, 0, 3); // applying transformation to the FOV triangle
        xpoints = new double[3];
        xpoints[0] = pArr[0].x;
        xpoints[1] = pArr[1].x;
        xpoints[2] = pArr[2].x;

        ypoints = new double[3];
        ypoints[0] = pArr[0].y;
        ypoints[1] = pArr[1].y;
        ypoints[2] = pArr[2].y;

    }

    public FOV(int camInd, int orient, ArrayList<Point2D.Double> cameras, double delta_angle) {
        double camX = cameras.get(camInd).x;
        double camY = cameras.get(camInd).y;
        AffineTransform t = new AffineTransform();
        t.rotate(orient * delta_angle, camX, camY);

        Point2D.Double[] pArr = {
            new Point2D.Double(camX, camY),
            // new Point2D.Double(camX + 505, camY - 505),
            // new Point2D.Double(camX + 710, camY) };
            new Point2D.Double(camX + 710, camY),
            new Point2D.Double(camX + 505, camY + 505)};
        t.transform(pArr, 0, pArr, 0, 3); // applying transformation to the FOV
        // triangle

        xpoints = new double[3];
        xpoints[0] = pArr[0].x;
        xpoints[1] = pArr[1].x;
        xpoints[2] = pArr[2].x;

        ypoints = new double[3];
        ypoints[0] = pArr[0].y;
        ypoints[1] = pArr[1].y;
        ypoints[2] = pArr[2].y;

    }

    public boolean contains(Point2D.Double p) {
        double px = p.x;
        double py = p.y;
        double o1 = getOrientationResult(xpoints[0], ypoints[0], xpoints[1], ypoints[1], px, py);
        double o2 = getOrientationResult(xpoints[1], ypoints[1], xpoints[2], ypoints[2], px, py);
        double o3 = getOrientationResult(xpoints[2], ypoints[2], xpoints[0], ypoints[0], px, py);

        return (o1 == o3) && (o1 == o2);
    }

    private int getOrientationResult(double x1, double y1, double x2, double y2, double px, double py) {
        double orientation = ((x2 - x1) * (py - y1)) - ((px - x1) * (y2 - y1));
        if (orientation > 0) {
            return 1;
        } else if (orientation < 0) {
            return -1;
        } else {
            return 0;
        }
    }
}
